package com.thn.netty.chat.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;

import java.nio.ByteBuffer;
import java.util.List;

import org.apache.log4j.Logger;

import com.google.protobuf.ByteString;
import com.thn.netty.chat.primitive.Command;
import com.thn.netty.chat.primitive.ErroCode;
import com.thn.netty.chat.primitive.LoginRequest;
import com.thn.netty.chat.primitive.PacketType;
import com.thn.netty.chat.primitive.UserName;
import com.thn.netty.chat.server.LoginParam;

/**
 * {@link DelegateCodec} implementation.
 * @author Thierry Herrmann
 */
public class LoginRequestCodec implements DelegateCodec {

	private static final Logger LOGGER = Logger.getLogger(LoginRequestCodec.class
			.getName());
	
	
//    @Override
//    public void decode(ChannelHandlerContext aCtx, ByteBuf aIn, List<Object> aOut) throws Exception {
//        Record rec = Record.read(aIn);
//        int cmdId = rec.getInt();
//        UserName userName = new UserName(rec.getString());
//        String password = rec.getString();
//        LoginRequest cmd = new LoginRequest(cmdId, userName, password);
//        aOut.add(cmd);
//    }
//    
//    @Override
//    public void encode(ChannelHandlerContext aCtx, Command aMsg, ByteBuf aOut) throws Exception {
//        LoginRequest cmd = (LoginRequest) aMsg;
//        Record rec = Record.forWrite();
//        rec.addInt(cmd.getId());
//        rec.addString(cmd.getUserName().getName());
//        rec.addString(cmd.getPassword());
//        rec.write(aOut);
//    }
	
    @Override
    public void decode(ChannelHandlerContext aCtx, ByteBuf aIn, List<Object> aOut) throws Exception {
    	short LOGIN_REQ=  aIn.getShort(8);	
    	if(LOGIN_REQ!=10)
    	{
    		//此处需要处理断开之前的操作，目前仅仅是把链接给强制断掉
    		aCtx.close();
    		return;
    	} 
    	short dataLength=  aIn.getShort(4);
    	
    	short paketTypeValue=  aIn.getShort(6);
    	
    	PacketType paketType= PacketType.forType(paketTypeValue);
    	
//    	IMPB.Message msgPacket;
//    	
//    	byte[] dataBytes=new byte[dataLength-10];
//    	aIn.getBytes(10, dataBytes);
//    	msgPacket=IMPB.Message.parseFrom(dataBytes);
    	
//    	Record rec = Record.read(aIn);
//        int cmdId = rec.getInt();
//        UserName userName = new UserName(rec.getString());
//        String password = rec.getString();
    	Command cmd=new Command(paketType,aIn);    	
        //LoginRequest cmd = new LoginRequest(cmdId, userName, password);
        
        
        aOut.add(cmd);
    	
    	
    	
//    	IMPB.Message.TYPE type=msgPacket.getType();
//    	IMPB.Message.SUB_TYPE sub_type=msgPacket.getSubType();
//    	
//    	if (type !=IMPB.Message.TYPE.CONNECTION) {
//    		LOGGER.error("Login Errcode:" +ErroCode.ERR_PARAM_PROTOCOL_MSG_TYPE_INVALID+"\n");    		
//    		return ;
//    	}
//    	if(sub_type == IMPB.Message.SUB_TYPE.CONNECTION_INITIAL)
//    	{
//    		//用户的sessionid需要判断下是否合法
//    		String sessionid =msgPacket.getId();
//    		LOGGER.info("type:"+type);
//    		LOGGER.info("sub_type:"+sub_type);
//    		LOGGER.info("登录成功！:"+sub_type);
//    		
//    		//登录成功
//    		
//    		IMPB.Message sessionMessage;
//    		sessionMessage=IMPB.Message.newBuilder().setType(IMPB.Message.TYPE.CONNECTION).setSubType(IMPB.Message.SUB_TYPE.CONNECTION_SUCCESS)
//    		.setId(sessionid) // sessionId
//            .build();
//    		
//    		// 拼接报文消息头10字节流
//    		ByteBuffer bHeader = ByteBuffer.allocate(CommandCodec.MSG_LEN_SIZE);
//    		bHeader.putInt(CommandCodec.headFirst); // 包标识  	
//    		short length = (short) ((short) (sessionMessage.toByteArray().length) + CommandCodec.MSG_LEN_SIZE);
//    		bHeader.putShort(4, length); // 包的长度
//    		bHeader.putShort(6, paketType); // 业务标识
//    		bHeader.putShort(8, CommandCodec.MSG_EXPAND);// 预留字段
//    		bHeader.flip();  
//    		// 拼接报文消息体的protobuf字节流
//    		ByteBuffer bContent = ByteBuffer.allocate(sessionMessage.toByteArray().length
//    				+ bHeader.array().length);
//    		bContent.put(bHeader);
//    		bContent.put(sessionMessage.toByteArray());    		
//    		ByteBuf buf = Unpooled.copiedBuffer(bContent);  
//    		aCtx.channel().write(buf);
//    		
//    		
//    		LoginParam loginParam=new LoginParam();
//    		loginParam.setSzSessionId(msgPacket.getId());
//    		loginParam.setUlUserid(msgPacket.getFrom());
//    		ByteString payLoad=msgPacket.getPayload();
//    		
//    		IMPB.Presence presence=IMPB.Presence.parseFrom(payLoad);    		
//    		loginParam.setUcLoginStatus(presence.getPresence().getNumber());    		
//    		loginParam.setUcLoginDevice(presence.getDeviceType().getNumber());
//    		
//    		
//    		if( IMPB.Presence.DEVICE_TYPE.IOS.getNumber()==loginParam.getUcLoginDevice())
//    		{
//    			//iospush_set_badge_number(loginParam.ulUserid,1);
//    		}
//    		loginParam.setUcLoginType(LoginParam.GET_LOGIN_TYPE(presence.getDeviceType().getNumber()));
//    		if (presence.hasNetworkType()) 
//    		{
//    			loginParam.setUcLoginNetworkType(presence.getNetworkType().getNumber());
//    		}
//    		else 
//    		{
//    			// PC可以不传这个可选参数    			
//    			loginParam.setUcLoginNetworkType(IMPB.Presence.NETWORK_TYPE.NET_ETHERNET.getNumber());
//    		}
//
//    		if ( presence.hasSwitchStatus())
//    		{
//    			loginParam.setUsLoginFreeswitchConn(presence.getSwitchStatus().getNumber());
//    			//RAW_LOG(INFO, "loginParam.usLoginFreeswitchConn: %d--------->\n", loginParam.usLoginFreeswitchConn );
//    		}
//    		else
//    		{
//    			loginParam.setUsLoginFreeswitchConn(IMPB.Presence.SWITCH_STATUS.UNCONNECT_VALUE);
//    		}   		
//    		LOGGER.info(
//    		 "login param:" +loginParam.getSzSessionId()+","+ loginParam.getUlUserid()+ "," +
//			(int)loginParam.getUcLoginType() + "," + (int)loginParam.getUcLoginStatus()
//			+ "," + (int)loginParam.getUcLoginDevice() + "," + loginParam.getUsLoginFreeswitchConn());
//    		
//    		if (!LoginParam.Presence_TYPE_IsValid(loginParam.getUcLoginStatus())
//    				|| !LoginParam.Presence_DEVICE_TYPE_IsValid(loginParam.getUcLoginDevice())) {
//    			LOGGER.error("Login param value is not in the range of protobuf emum!");
//    				return ;
//    			}
//    		
//    		Boolean bAddLoginNum = false;    		
//    		//AddSession(c, &loginParam, &bAddLoginNum);
//    		if (bAddLoginNum) 
//    		{
//    			
//    			
//    		}
//    		
//    		
//    		//AddSession
//    		
//    	}
//    	else if(sub_type == IMPB.Message.SUB_TYPE.CONNECTION_HB)
//    	{
//    		// 心跳
//    		LOGGER.info("心跳:" +sub_type);
//    		// 
//    		// PC客户端回一个心跳
//    		IMPB.Presence.DEVICE_TYPE.UNKNOWN.getNumber();
////    		if (GetUserLoginDeviceType(c) == im::Presence_DEVICE_TYPE_PC)
////    		{
////    			LOG(INFO) << "PC心跳:" << sub_type << "\n";
////    			evbuffer_add(c->out_buf,c->in_buf,hreq->pkglen);
////    			event_active(&c->bufev->ev_write, EV_WRITE, 1);
////    		}
//    	}
//    	else if(sub_type == IMPB.Message.SUB_TYPE.CONNECTION_IOSTOKEN)
//    	{
//    	
//    	} 
    	
    	
//    	Record rec = Record.read(aIn);
//        int cmdId = rec.getInt();
//        UserName userName = new UserName(rec.getString());
//        String password = rec.getString();
//        LoginRequest cmd = new LoginRequest(cmdId, userName, password);
//        aOut.add(cmd);
    }
    
    @Override
    public void encode(ChannelHandlerContext aCtx, Command aMsg, ByteBuf aOut) throws Exception {
      ByteBuf msgData=aMsg.getMsgData();	
      aOut.writeBytes(msgData);
//        LoginRequest cmd = (LoginRequest) aMsg;
//        Record rec = Record.forWrite();
//        rec.addInt(cmd.getId());
//        rec.addString(cmd.getUserName().getName());
//        rec.addString(cmd.getPassword());
//        rec.write(aOut);
    }

}
